package qq.android.wan.qq;

import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.Application;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.util.Log;

import com.baidu.mapapi.SDKInitializer;
import com.easemob.EMConnectionListener;
import com.easemob.EMError;
import com.easemob.EMEventListener;
import com.easemob.EMNotifierEvent;
import com.easemob.chat.EMChat;
import com.easemob.chat.EMChatManager;
import com.easemob.chat.EMMessage;
import com.easemob.chat.ImageMessageBody;
import com.easemob.chat.LocationMessageBody;
import com.easemob.chat.TextMessageBody;
import com.easemob.chat.VoiceMessageBody;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import de.greenrobot.event.EventBus;
import qq.android.wan.qq.activity.MainActivity;
import qq.android.wan.qq.chat.activity.ChatActivity;
import qq.android.wan.qq.db.dao.SessionDao;
import qq.android.wan.qq.entity.SessionBean;
import qq.android.wan.qq.event.ChatEvent;
import qq.android.wan.qq.recever.CallReceiver;


/**
 * Created by Administrator on 2015/12/18.
 */
public class MyApplication extends Application implements EMEventListener {
    public static String toChatUser = "-1";       //默认和谁聊天
    private Notification notification;
    private File soundFile;
    //public static DemoHXSDKHelper hxSDKHelper = new DemoHXSDKHelper();

    @Override
    public void onCreate() {
        super.onCreate();
        SDKInitializer.initialize(this);
        int pid = android.os.Process.myPid();
        String processAppName = getAppName(pid);
// 如果app启用了远程的service，此application:onCreate会被调用2次
// 为了防止环信SDK被初始化2次，加此判断会保证SDK被初始化1次
// 默认的app会在以包名为默认的process name下运行，如果查到的process name不是app的process name就立即返回

        if (processAppName == null || !processAppName.equalsIgnoreCase("qq.android.wan.qq")) {
            //"com.easemob.chatuidemo"为demo的包名，换到自己项目中要改成自己包名

            // 则此application::onCreate 是被service 调用的，直接返回
            return;
        }
        EMChat.getInstance().init(this);
        EMChatManager.getInstance().registerEventListener(this,
                new EMNotifierEvent.Event[]{EMNotifierEvent.Event.EventNewMessage,
                        EMNotifierEvent.Event.EventOfflineMessage, EMNotifierEvent.Event.EventDeliveryAck,
                        EMNotifierEvent.Event.EventReadAck});
        IntentFilter callFilter = new IntentFilter(EMChatManager.getInstance().getIncomingCallBroadcastAction());
        CallReceiver callReceiver = new CallReceiver();
        //注册通话广播接收者
        registerReceiver(callReceiver, callFilter);
        EMChatManager.getInstance().addConnectionListener(new MyConnectionListener());
    }


    @Override
    public void onEvent(EMNotifierEvent emNotifierEvent) {
        switch (emNotifierEvent.getEvent()) {

            case EventNewMessage:
                EMMessage message = (EMMessage) emNotifierEvent.getData();
                if (message.getFrom().equals(MyApplication.toChatUser)) {
                    //说明当前正在和该人聊天，我们发送广播
                    Intent intent = new Intent();
                    intent.setAction("chat");
                    intent.putExtra("date", message);
                    sendBroadcast(intent);
                } else {
                    EventBus.getDefault().post(ChatEvent.UPDATE_UNREAD_NUM);
                    showNotification(message);
                }
                break;
        }
    }

    /**
     * 当收到新的消息是在通知栏显示
     */
    private void showNotification(EMMessage message) {
        String str_bar = null;
        String str_title = null;
        String str_conteent = null;
        String lastMessage="";
        if (message.getType() == EMMessage.Type.TXT) {
            //收到的是文本消息
            TextMessageBody textMessageBody = (TextMessageBody) message.getBody();
            str_bar = "你收到了一条来自" + message.getFrom() + "的消息";
            str_title = message.getFrom();
            str_conteent = textMessageBody.getMessage();
            lastMessage=str_conteent;
        } else if (message.getType() == EMMessage.Type.IMAGE) {
            //收到的是图片消息
            ImageMessageBody textMessageBody = (ImageMessageBody) message.getBody();
            str_bar = "你收到了一张来自" + message.getFrom() + "的图片";
            str_title = message.getFrom();
            str_conteent = "一张图片消息";
            lastMessage="[图片]";
        } else if (message.getType() == EMMessage.Type.VOICE) {
            //收到的是语音消息
            VoiceMessageBody textMessageBody = (VoiceMessageBody) message.getBody();
            str_bar = "你收到了一条来自" + message.getFrom() + "的语音消息";
            str_title = message.getFrom();
            str_conteent = "一条语音消息";
            lastMessage="[语音]";
        } else if (message.getType() == EMMessage.Type.LOCATION) {
            //收到的是语音消息
            LocationMessageBody textMessageBody = (LocationMessageBody) message.getBody();
            str_bar = "你收到了一条来自" + message.getFrom() + "的位置消息";
            str_title = message.getFrom();
            str_conteent = "一条位置消息";
            lastMessage="[位置]";
        }
        NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        if (notification == null) {
            notification = new Notification();
        }
        if (soundFile == null) {
            //  soundFile=getRAWFile();
        }
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
        builder.setAutoCancel(true);
        builder.setColor(NotificationCompat.DEFAULT_LIGHTS);
        builder.setContentTitle(str_title)
                //.setContentInfo(str_conteent)
                .setContentText(str_conteent)
                .setSmallIcon(R.drawable.ee_2);
        builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ziji));
        builder.setSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.new_message));
        builder.setLights(NotificationCompat.DEFAULT_LIGHTS, 800, 800);
        Intent intent = new Intent(this, ChatActivity.class);
        intent.putExtra("qqId",message.getFrom());
        intent.putExtra("nick",message.getUserName());
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT);
        builder.setContentIntent(pendingIntent);
        notificationManager.notify(1234, builder.build());
        //查看在本地session表中是否有该用户
        SessionDao sessionDao=new SessionDao(getApplicationContext());
        if(sessionDao.isExistByqqId(Integer.parseInt(message.getFrom()))){
            //修改
            sessionDao.updateLastMessage(lastMessage,Integer.parseInt(message.getFrom()));
        }else {
            //插入
            SessionBean sessionBean=new SessionBean();
            sessionBean.setUserId(Integer.parseInt(message.getFrom()));
            sessionBean.setNick(message.getUserName() + message.getFrom());
            sessionBean.setLastMessage(lastMessage);
            sessionDao.insert(sessionBean);
        }
        EventBus.getDefault().post(ChatEvent.UPDATE_SESSION_LASTMESSAGE);
    }

    private String getAppName(int pID) {
        String processName = null;
        ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
        List l = am.getRunningAppProcesses();
        Iterator i = l.iterator();
        PackageManager pm = this.getPackageManager();
        while (i.hasNext()) {
            ActivityManager.RunningAppProcessInfo info = (ActivityManager.RunningAppProcessInfo) (i.next());
            try {
                if (info.pid == pID) {
                    CharSequence c = pm.getApplicationLabel(pm.getApplicationInfo(info.processName, PackageManager.GET_META_DATA));
                    // Log.d("Process", "Id: "+ info.pid +" ProcessName: "+
                    // info.processName +"  Label: "+c.toString());
                    // processName = c.toString();
                    processName = info.processName;
                    return processName;
                }
            } catch (Exception e) {
                // Log.d("Process", "Error>> :"+ e.toString());
            }
        }
        return processName;
    }
    //注册一个监听连接状态的listener


    //实现ConnectionListener接口
    private class MyConnectionListener implements EMConnectionListener {
        @Override
        public void onConnected() {
            //已连接到服务器
            Log.e("test","连接服务器成功");
        }

        @Override
        public void onDisconnected(final int error) {
            if (error == EMError.USER_REMOVED) {
                // 显示帐号已经被移除
                Log.e("test","帐号已经被移除");

            } else if (error == EMError.CONNECTION_CONFLICT) {
                // 显示帐号在其他设备登陆
                Log.e("test","帐号在其他设备登陆");
            } else {
                Log.e("test","重连失败"+error);
            }
        }
    }
}
